package com.gulimall.seckill.interceptor;

import com.alibaba.fastjson2.JSONObject;
import com.gulimall.common.constrant.AuthServerConstant;
import com.gulimall.common.vo.MemberRespVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author kkk
 * @date 2022/8/11
 */
@Component
public class SeckillInterceptor implements HandlerInterceptor {
    public static final ThreadLocal<MemberRespVo> THREAD_LOCAL = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        boolean match = new AntPathMatcher().match("/seckill", requestURI);
        HttpSession session = request.getSession();
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_INFO);
        MemberRespVo memberRespVo = attribute == null ? null :
                JSONObject.parseObject(JSONObject.toJSONString(attribute), MemberRespVo.class);
        if (match) {
            if (memberRespVo == null) {
                session.setAttribute("msg", "请先登录");
                response.sendRedirect("http://auth.gulimall.com/login.html");
                return false;
            } else {
                THREAD_LOCAL.set(memberRespVo);
                return true;
            }
        }
        THREAD_LOCAL.set(memberRespVo);
        return true;
    }
}
